//
//  GPS.m
//  HelloWorld
//
//  Created by Vitor Venturin Linhalis on 16/12/14.
//
//

#import "GPS.h"
#import <Cordova/CDV.h>

@implementation GPS

CLLocationManager *locationManager;
static double lat;
static double lng;
static NSString *callbackid;
static UIAlertView *alertView;
static UIAlertController *alertCtrl;
static bool cancel;
static bool not_keep_location=NO;

- (void)getLocation:(CDVInvokedUrlCommand*)command
{
    NSNumber *num=(NSNumber *)[command argumentAtIndex:0];
    not_keep_location=[num boolValue];
    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    if(IS_OS_8_OR_LATER) {
        NSLog(@"=================>IOS 8=====================");
        if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [locationManager requestWhenInUseAuthorization];
        }
    }else{
        NSLog(@"=====================<IOS 8===============");
    }

    [locationManager startUpdatingLocation];
    callbackid=command.callbackId;
}

#pragma mark - CLLocationManagerDelegate

- (void)stopLocation:(CDVInvokedUrlCommand*)command
{
    [self stopLocation];
}

- (void)stopLocation
{
    callbackid=nil;
    [locationManager stopUpdatingLocation];
}
- (void)requestWhenInUseAuthorization
{

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"定位服务已经关闭" : @"应用或其功能在屏幕上显示时才能访问您的位置";
        NSString *message = @"请设置允许应用使用定位服务";
        if(IS_OS_8_OR_LATER) {
            if(alertCtrl==nil){
                alertCtrl=[UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    cancel=YES;
                    
                }];
                UIAlertAction *settingAction=[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:settingsURL];
                    
                }];
                [alertCtrl addAction:cancelAction];
                [alertCtrl addAction: settingAction];
            }
            if(self.viewController.presentedViewController==nil&&alertCtrl!=nil){
                [self.viewController presentViewController:alertCtrl animated:YES completion:nil];
            }

        }else{
            if(alertView==nil){
          
                alertView = [[UIAlertView alloc] initWithTitle:title
                                                       message:@"请打开“定位服务”来允许“勘察系统”确定您的位置"
                                                      delegate:self
                                             cancelButtonTitle:@"我知道了"
                                             otherButtonTitles:nil, nil];
                [alertView show];
            }else{
                if(![alertView isVisible]){
                    [alertView show];
                }
                
            }
            
        }
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [locationManager requestWhenInUseAuthorization];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
     cancel=YES;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLocation = [locations lastObject];

    if (currentLocation != nil) {
        NSDate* eventDate = currentLocation.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        //  NSLog(@"%f===============%lu======",fabs(howRecent),locations.count);
        if (fabs(howRecent) < 15.0) {
            // If the event is recent, do something with it.
            lat = currentLocation.coordinate.latitude;
            lng = currentLocation.coordinate.longitude;
        }
        NSLog(@"%f===========%f==========",lat,lng);
        if(lat>0&&lng>0&&callbackid){

            CDVPluginResult* pluginResult = nil;
            NSArray *vetor = [[NSArray alloc] initWithObjects:[NSNumber numberWithDouble:lat],[NSNumber numberWithDouble:lng],nil];

            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:vetor];
            [pluginResult setKeepCallbackAsBool:TRUE];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackid];
            if(not_keep_location){
                [self stopLocation];
            }
        }

    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oi" message:[NSString stringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    // [alert show];
    if(callbackid){
        CDVPluginResult *pluginResult = nil;
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"%@",error]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackid];
    }
    if(!cancel){
        [self requestWhenInUseAuthorization];
    }
}

@end
